package com.bc.web.controller.org;

import java.util.HashSet;
import java.util.Set;

import com.bc.web.interceptors.AuthInterceptor;
import com.bc.web.model.Org;
import com.bc.web.model.OrgRole;
import com.bc.web.model.OrgUser;
import com.fs.common.auth.FSAuth;
import com.fs.common.extend.FSController;
import com.fs.common.util.FSMD5;
import com.jfinal.aop.Clear;

@Clear
public class MainController extends FSController{
	
	public void loginpage(){
		render("login.html");
	}
	
	public void login(){
		if(!validateCaptcha("captchaCode")){
			renderFail("验证码错误.");
		}else{
			String userName = getPara("userName");
			String password = FSMD5.codeFor(getPara("password"));
			OrgUser loginUser = OrgUser.dao.loginFind(userName, password);
			if(loginUser != null){
				if(loginUser.getEnable() == false){
					renderFail("用户被禁用");
				}else{
					OrgRole role = OrgRole.dao.findById(loginUser.getRoleId());
					if(role == null){
						renderFail("无角色用户,无法登录");
					}else {
						
						getSession().setAttribute("orgUser", loginUser);
						getSession().setAttribute("org", Org.dao.selectByOrgCode(loginUser.getOrgCode()));
						getSession().setAttribute("sidebar", AuthInterceptor.getSidebar_org_zh_CN());
						setAuthAttr(role);
						renderSuccess();
					}
				}
			}else{
				renderFail("用户名/密码错误");
			}
		}
	}
	
	/**
	 * 将拥有的权限设置到session供标签使用
	 * @param role
	 */
	private void setAuthAttr(OrgRole role){
		//菜单明细url
		String[] split = role.getSourceUrl().split(",");
		Set<String> menuUrl = new HashSet<>();
		for (String temp : split) {
			menuUrl.add(temp);
		}
		getSession().setAttribute("ORG" + FSAuth.MENU_URL, menuUrl);
		
		//菜单组
		split = role.getSourceGroup().split(",");
		Set<String> menuGroup = new HashSet<>();
		for (String temp : split) {
			menuGroup.add(temp);
		}
		getSession().setAttribute("ORG" + FSAuth.MENU_GROUP, menuGroup);
		
	}
	
	/**
	 * 获取验证码
	 */
	public void getCaptchaCode(){
		renderCaptcha();
	}

	
	public void logout(){
		getSession().removeAttribute("orgUser");
		redirect("/org/loginpage");
	}

}
